#include <unistd.h>
#include <zcm/zcm-cpp.hpp>
#include "HELLO.hpp"
#include <iostream>
#include <string>
#include <string.h>
#include <chrono>
#include <hiredis/hiredis.h>
using namespace std;
#define IP "127.0.0.1"
#define PORT 6379
#define CHANNEL "TEST"
int main(int argc, char *argv[])
{
    char ip[16] = IP, channel[20] = CHANNEL;
    int port = PORT;
    char buf[200];
    switch (argc)
    {
    case 4:
        strcpy(channel, argv[3]);
    case 3:
        port = stoi(argv[2]);
    case 2:
        strcpy(ip, argv[1]);
    }
    redisReply *reply = NULL;
    // 连接服务器
    redisContext *context = redisConnect(ip, port);
    if (context->err)
    {
        std::cout << "can not connect to redisserver" << endl;
        std::cout << "reason:" << context->errstr << endl;
        redisFree(context);
        context = NULL;
        return 0;
    }

    HELLO my_data{};
    my_data.str = "Hello!";

    while (true)
    {
        chrono::milliseconds ms = chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now().time_since_epoch());
        my_data.time = to_string(ms.count());
        // 编码zcm数据
        int ret = my_data.encode(buf, 0, 200);
        // buf[ret] = '\0';
        // 传输二进制字符串需要手动指定长度
        reply = (redisReply *)redisCommand(context, "publish %s %b", CHANNEL, buf, ret);
        if (NULL == reply || reply->type != REDIS_REPLY_INTEGER) //成功推送几个就会有几个 integer
        {
            break;
        }
        cout << "send a message." << endl;
        sleep(5);
        freeReplyObject(reply);
    }
    if (reply != NULL)
        freeReplyObject(reply);
    redisFree(context);
    context = NULL;
    return 0;
    return 0;
}